﻿using AutoMapper;
using lwzlz.Application.System.Dto;
using lwzlz.Core;
using lwzlz.Core.Repository;
using System;
using System.Collections.Generic;

namespace lwzlz.Application.System
{
    public class MenuBtnService
    {
        private readonly IRepository<Menu> _repository;

        public MenuBtnService()
        {
            _repository = new Repository<Menu>();
        }

        #region 按钮

        #region 获取按钮

        /// <summary>
        /// 获取按钮
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ButtonOutput GetButton(int id)
        {
            var entity = _repository.Get(id);
            return Mapper.Map<ButtonOutput>(entity);
        }

        /// <summary>
        /// 获取按钮列表
        /// </summary>
        /// <param name="whereConditions"></param>
        /// <returns></returns>
        public IEnumerable<ButtonOutput> GetButtonList(object whereConditions)
        {
            var btnList = _repository.GetList(whereConditions);
            return Mapper.Map<IEnumerable<ButtonOutput>>(btnList);
        }

        #endregion

        #region 编辑按钮

        /// <summary>
        /// 添加按钮
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int? AddButton(ButtonInput model)
        {
            var entity = Mapper.Map<Menu>(model);
            var parent = _repository.Get(model.ParentId);

            entity.MenuType = 2;
            entity.MenuDeep = parent.MenuDeep + 1;
            entity.MenuArea = parent.MenuArea;
            entity.MenuControl = parent.MenuControl;
            entity.MenuUrl = $"/{entity.MenuArea}/{entity.MenuControl}/{entity.MenuAction}";
            entity.IsDeleted = false;
            entity.CreationTime = DateTime.Now;
            entity.CreatorUserID = UserAuthentication.GetCurrentUser().UserID;

            return _repository.Insert(entity);
        }

        /// <summary>
        /// 修改按钮
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int EditButton(ButtonInput model)
        {
            var entity = _repository.Get(model.Id);

            Mapper.Map(model, entity);
            entity.MenuUrl = $"/{entity.MenuArea}/{entity.MenuControl}/{entity.MenuAction}";
            entity.LastModificationTime = DateTime.Now;
            entity.LastModifierUserId = UserAuthentication.GetCurrentUser().UserID;

            return _repository.Update(entity);
        }

        #endregion

        #endregion
    }
}
